package com.example.admin.service;

import com.example.admin.pojo.Admin;
import com.example.admin.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

//自定义service 来去实现实时的权限认证
@Service
public class AuthService
{
    @Autowired
    private AdminService adminService;

    //权限认证
    public boolean auth(HttpServletRequest request, Authentication authentication)
    {
        //请求路径
        String requestURI = request.getRequestURI();
        //匿名用户
        Object principal = authentication.getPrincipal();
        if (principal == null || "anonymousUser".equals(principal))
        {
            //未登录
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        String password = userDetails.getPassword();
        Admin admin = adminService.findAdminByUsernameAndPassword(username,password);
        if (admin == null)
        {
            return false;
        }
        //最高权限者
        if (admin.getId() == 1)
        {
            return true;
        }
        Long id = admin.getId();
        List<Permission> permissionList = adminService.findPermissionByAdminId(id);

        //requestURI可能有?后面的参数传参，所以要分割一下
        requestURI = StringUtils.split(requestURI, "?")[0];
        for (Permission permission : permissionList) {
            //判断该用户有没有这个请求路径的权限
            if (requestURI.equals(permission.getPath())) {
                return true;
            }
        }
        return false;
    }
}
